<?php


namespace Lib\Component;


class Uri implements ComponentInterface
{
    private static $instance = null;
    private static $pathInfoArr = array();

    private function __construct()
    {
    }

    /**
     * 获取单例对象
     * @return Uri|null
     */
    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new static();
            self::$instance->register();
        }
        return self::$instance;
    }

    /**
     * 解析uri
     */
    public function register()
    {
        $requestUri = $_SERVER['REQUEST_URI'];
        if ($requestUri !== '/') {
            $requestUri = explode('?', $requestUri);
            $requestUri = $requestUri[0];
            $requestUri = trim($requestUri, '/');
            self::$pathInfoArr = explode('/', $requestUri);
        }
    }

    /**
     * 获取uri片段
     * @param int $index
     * @return bool|string
     */
    public function segment($index = 1)
    {
        $index = $index - 1;
        if (isset(self::$pathInfoArr[$index])) {
            return htmlspecialchars(self::$pathInfoArr[$index]);
        } else {
            return false;
        }
    }
}